import requests
import json
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
import tkinter as tk
import tkinter.font as tf
from tkinter import ttk


#腾讯上的两个疫情数据包
def get_data1():
    url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=jQuery341001657575837432268_1581070969707&_=1581070969708'
    headers = {'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36'}
    res = requests.get(url, headers=headers).text
    a = res.split('jQuery341001657575837432268_1581070969707(')[1].split(')')[0]
    c = json.loads(a)
    data1 = json.loads(c['data'])
    return data1

def get_data2():
    url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_other&callback=jQuery34109115895667113716_1582869774819&_=1582869774820'
    headers = {'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36'}
    res = requests.get(url, headers=headers).text
    #res = requests.get(url).text
    a = res.split("jQuery34109115895667113716_1582869774819(")
    b=a[1]
    d=b[0:-1]
    c = json.loads(d)
    data2 = json.loads(c['data'])
    return data2

data1 = get_data1()

window = tk.Tk()
window.title("疫情实时数据查询")
window.geometry("950x450")
window.resizable(0,0)

t1=tk.Text(window,width=80,height=1,font=tf.Font(size=15))
t1.pack(side=tk.TOP)
t1.insert("end","         "+"统计截至时间："+str(data1['lastUpdateTime'])+"        "+"数据来源：腾讯实时疫情")

t2=tk.Text(window,width=100,height=1,font=tf.Font(size=15),foreground="red")
t2.pack(side=tk.TOP)
t2.insert("end","                       "+"全国累计确诊人数："+str(data1['chinaTotal']['confirm'])+"        "+"相较于昨天新增确诊人数："+str(data1['chinaAdd']['confirm']))


t3=tk.Text(window,width=100,height=1,font=tf.Font(size=15),foreground="yellow")
t3.pack(side=tk.TOP)
t3.insert("end","                       "+"全国疑似病例："+str(data1['chinaTotal']['suspect'])+"        "+"相较于昨天新增疑似人数："+str(data1['chinaAdd']['suspect']))

t4=tk.Text(window,width=100,height=1,font=tf.Font(size=15),foreground="green")
t4.pack(side=tk.TOP)
t4.insert("end","                       "+"全国治愈人数："+str(data1['chinaTotal']['heal'])+"         "+"相较于昨天新增治愈人数："+str(data1['chinaAdd']['heal']))


t5=tk.Text(window,width=100,height=1,font=tf.Font(size=15),foreground="gray")
t5.pack(side=tk.TOP)
t5.insert("end","                       "+"全国死亡人数："+str(data1['chinaTotal']['dead'])+"          "+"相较于昨天新增死亡人数："+str(data1['chinaAdd']['dead']))

t6=tk.Text(window,width=80,height=0.6,font=tf.Font(size=15),foreground="black")
t6.pack(side=tk.TOP)
t6.insert("end","请在下方输入您要查询的省份（或直辖市）例：北京")

#一个entry输入框
e1=tk.Entry(window,width=48)
e1.pack(side=tk.TOP)

#滚动条
scrollBar = tk.Scrollbar(window)
scrollBar.pack(side=tk.RIGHT,fill = tk.Y)
#创建一个tree表格
tree = ttk.Treeview(window,show='headings',yscrollcommand=scrollBar.set)


flag=0
def print_children():
    global flag
    
    def delButton(tree):
        x=tree.get_children()
        for item in x:
            tree.delete(item)

    if flag!=0:
        delButton(tree)
        
    data1 = get_data1()['areaTree'][0]['children']
    path = str(e1.get())
    path_data = []
    path_china = []

    for i in data1:
        path_china.append(i['name'])
        path_data.append(i['children'])
    if path in path_china:
        num = path_china.index(path)
        data_path = path_data[num]

        ttk.Treeview.column(tree,"#0",width=100,anchor="center")
        tree["columns"] = ('地区','累计确诊人数','相较于昨日新增确诊人数','累计疑似病例','确诊减少人数','累计治愈人数','治愈率','累计死亡人数','死亡率') 
        tree.column('地区', width=80)
        tree.column('累计确诊人数', width=100)
        tree.column('相较于昨日新增确诊人数', width=150)
        tree.column('累计疑似病例', width=100)
        tree.column('确诊减少人数', width=100)
        tree.column('累计治愈人数', width=100)
        tree.column('治愈率', width=100)
        tree.column('累计死亡人数', width=100)
        tree.column('死亡率', width=100)

        tree.heading('地区', text='地区')
        tree.heading('累计确诊人数', text='累计确诊人数') 
        tree.heading('相较于昨日新增确诊人数', text='相较于昨日新增确诊人数') 
        tree.heading('累计疑似病例', text='累计疑似病例') 
        tree.heading('确诊减少人数', text='确诊减少人数') 
        tree.heading('累计治愈人数', text='累计治愈人数') 
        tree.heading('治愈率', text='治愈率') 
        tree.heading('累计死亡人数', text='累计死亡人数') 
        tree.heading('死亡率', text='死亡率')
        
        h=0
        for i in data_path:
            name = i['name']
            today = i['today']
            total = i['total']
            tree.insert("",h, text = name, values=(name,str(total['confirm']), str(today['confirm']), str(total['suspect']), str(today['confirmCuts']), str(total['heal']), str(total['healRate']), str(total['dead']), str(total['deadRate'])))
            h+=1
            flag = 1
        tree.pack()
        scrollBar.config(command=tree.yview)

    else:
        t6.insert("end","无此省（或直辖市），请重启程序")




def other_functions():
    window1 = tk.Tk()
    window1.title("其他功能")
    window1.geometry("400x300")
    window1.resizable(0,0)


    def draw_daily_add_line():
        datas = get_data2()["dailyNewAddHistory"]
        x1 = []
        y1 = []
        y2 = []
        y3 = []
        for data in datas:
            y1.append(data["country"])
            y2.append(data["hubei"])
            y3.append(data["notHubei"])
        for i in range(1,(len(y1)+1),1):
            x1.append(i)
        plt.figure(num = "疫情每日新增图")
        plt.xlabel("date,from 2019.1.20 to now")
        plt.ylabel("number")
        ax = plt.gca()
        ax.spines["top"].set_color("none")
        ax.spines["right"].set_color("none")
        ax.xaxis.set_ticks_position("bottom")
        ax.yaxis.set_ticks_position("left")
        plt.xlim(1,(len(y1)+1))
        plt.ylim(0,16000)
        plt.plot(x1,y1,label = "Whole country")
        plt.plot(x1,y2,label = "Hubei region")
        plt.plot(x1,y3,label = "Non Hubei region")
        plt.xticks([])
    
        plt.legend()
        plt.show()

    def draw_now_confirm_line():
        datas = get_data2()["dailyHistory"]
        x1 = []
        y1 = []
        y2 = []
        y3 = []
        i=0
        for data in datas:
            x1.append(i+1)
            y1.append(data["country"]["nowConfirm"])
            y2.append(data["hubei"]["nowConfirm"])
            y3.append(data["notHubei"]["nowConfirm"])
            i+=1
        plt.figure(num = "疫情现有确诊图")
        plt.xlabel("date,from 2019.1.20 to now")
        plt.ylabel("number")
        ax = plt.gca()
        ax.spines["top"].set_color("none")
        ax.spines["right"].set_color("none")
        ax.xaxis.set_ticks_position("bottom")
        ax.yaxis.set_ticks_position("left")
        plt.xlim(1,(len(y1)+1))
        plt.ylim(0,60000)
        plt.plot(x1,y1,label = "Whole country")
        plt.plot(x1,y2,label = "Hubei region")
        plt.plot(x1,y3,label = "Non Hubei region")
        plt.xticks([])
    
        plt.legend()
        plt.show()

    def draw_sum_confirm_line():
        datas = get_data2()["chinaDayList"]
        x1 = []
        y1 = []
        i=0
        for data in datas:
            x1.append(i+1)
            y1.append(data["confirm"])
            i+=1
        plt.figure(num = "疫情累计确诊图")
        plt.xlabel("date,from 2019.1.20 to now")
        plt.ylabel("number")
        ax = plt.gca()
        ax.spines["top"].set_color("none")
        ax.spines["right"].set_color("none")
        ax.xaxis.set_ticks_position("bottom")
        ax.yaxis.set_ticks_position("left")
        plt.xlim(1,(len(y1)+1))
        plt.ylim(0,90000)
        plt.plot(x1,y1,label = "Whole country")
        plt.xticks([])
        plt.legend()
        plt.show()

    def insert_news():
        url = "http://wjw.beijing.gov.cn/"
        headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0"}
        html = requests.get(url , headers = headers).text
        soup = BeautifulSoup(html,"lxml")
        news_path1 = soup.find_all("div",{"class":"main_con_weinei_syx"})[1]
        news_path2 = news_path1.find("div",{"class":"weinei_left_syx"})
        news_path3 = news_path2.find("div",{"class":"wenhua_left_consy_syx"})
        news_tags = news_path3.find_all("div",{"class":"wenhua_left_consy_line_text_syx"})
        for news_tag1 in news_tags:
            news = news_tag1.get_text()
           


    bb1 = tk.Button(window1,width=40,text = "查看疫情每日新增图",command = draw_daily_add_line)
    bb1.grid()
    bb2 = tk.Button(window1,width=40,text = "查看疫情当前确诊图",command = draw_now_confirm_line)
    bb2.grid()
    bb3 = tk.Button(window1,width=40,text = "查看疫情累计确诊图",command = draw_sum_confirm_line)
    bb3.grid()
    bb4 = tk.Button(window1,width=40,text = "查看",command = insert_news)
    bb4.grid()
    window1.mainloop()


b1=tk.Button(window,width=68,text="点击查看该地区详细情况",command=print_children)
b1.pack(side=tk.TOP)
b2 = tk.Button(window,width = 68,text = "点击使用其他功能",command = other_functions)
b2.pack()
window.mainloop()


